<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

interface Resident {
  id: number
  name: string
  age: number
  room: string
  healthStatus: string
  emergencyContact: string
}

const residents = ref<Resident[]>([])
const dialogVisible = ref(false)
const loading = ref(false)
const isEdit = ref(false)
const currentId = ref<number | null>(null)

const formData = ref({
  name: '',
  age: 0,
  room: '',
  healthStatus: '稳定',
  emergencyContact: ''
})

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  room: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  healthStatus: [{ required: true, message: '请选择健康状态', trigger: 'change' }],
  emergencyContact: [{ required: true, message: '请输入紧急联系人', trigger: 'blur' }]
}

// Fetch residents from API
const fetchResidents = async () => {
  try {
    loading.value = true
    const response = await fetch('http://localhost:3000/api/residents')
    if (!response.ok) throw new Error('获取数据失败')
    const data = await response.json()
    residents.value = Array.isArray(data) ? data : []
  } catch (error) {
    ElMessage.error('获取住户列表失败')
    residents.value = []
  } finally {
    loading.value = false
  }
}

// Add new resident
const addResident = async () => {
  try {
    const response = await fetch('http://localhost:3000/api/residents', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData.value)
    })

    if (!response.ok) throw new Error('添加失败')
    
    ElMessage.success('添加住户成功')
    dialogVisible.value = false
    await fetchResidents()
    resetForm()
  } catch (error) {
    ElMessage.error('添加住户失败')
  }
}

// Edit resident
const editResident = async () => {
  if (!currentId.value) return
  
  try {
    const response = await fetch(`http://localhost:3000/api/residents/${currentId.value}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData.value)
    })

    if (!response.ok) throw new Error('更新失败')
    
    ElMessage.success('更新住户成功')
    dialogVisible.value = false
    await fetchResidents()
    resetForm()
  } catch (error) {
    ElMessage.error('更新住户失败')
  }
}

// Delete resident
const deleteResident = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该住户吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await fetch(`http://localhost:3000/api/residents/${id}`, {
      method: 'DELETE'
    })

    if (!response.ok) throw new Error('删除失败')
    
    ElMessage.success('删除住户成功')
    await fetchResidents()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除住户失败')
    }
  }
}

// Handle edit button click
const handleEdit = (row: Resident) => {
  isEdit.value = true
  currentId.value = row.id
  formData.value = { ...row }
  dialogVisible.value = true
}

// Handle add button click
const handleAdd = () => {
  isEdit.value = false
  currentId.value = null
  resetForm()
  dialogVisible.value = true
}

const handleSubmit = () => {
  if (isEdit.value) {
    editResident()
  } else {
    addResident()
  }
}

const resetForm = () => {
  formData.value = {
    name: '',
    age: 0,
    room: '',
    healthStatus: '稳定',
    emergencyContact: ''
  }
}

onMounted(() => {
  fetchResidents()
})
</script>

<template>
  <div class="residents">
    <div class="header">
      <h2>住户管理</h2>
      <el-button type="primary" @click="handleAdd">添加住户</el-button>
    </div>

    <el-table 
      :data="residents" 
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="room" label="房间号" width="100" />
      <el-table-column prop="healthStatus" label="健康状态">
        <template #default="{ row }">
          <el-tag :type="row.healthStatus === '稳定' ? 'success' : row.healthStatus === '需要关注' ? 'warning' : 'danger'">
            {{ row.healthStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="emergencyContact" label="紧急联系人" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="danger" @click="deleteResident(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Add/Edit Resident Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑住户' : '添加住户'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="formData.age" :min="0" :max="150" />
        </el-form-item>
        <el-form-item label="房间号" prop="room">
          <el-input v-model="formData.room" />
        </el-form-item>
        <el-form-item label="健康状态" prop="healthStatus">
          <el-select v-model="formData.healthStatus" style="width: 100%">
            <el-option label="稳定" value="稳定" />
            <el-option label="需要关注" value="需要关注" />
            <el-option label="需要护理" value="需要护理" />
          </el-select>
        </el-form-item>
        <el-form-item label="紧急联系人" prop="emergencyContact">
          <el-input v-model="formData.emergencyContact" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.residents {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>